package ynu.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.mapper.IOrderDetailetMapper;
import ynu.edu.mapper.IOrdersMapper;
import ynu.edu.po.OrderDetailet;
import ynu.edu.po.Orders;
import ynu.edu.service.IOrderDetailetService;

import java.util.List;

@Service
public class OrderDetailetServiceImpl implements IOrderDetailetService {
    @Resource
    private IOrderDetailetMapper orderDetailetMapper;

    @Resource
    private IOrdersMapper ordersMapper;

    @Override
    @Transactional
    public boolean saveOrderDetailetBatch(List<OrderDetailet> list) {
        if (list == null || list.isEmpty()) {
            return false; // 如果没有数据要插入，返回 false
        }

        for (OrderDetailet detail : list) {
            int result = orderDetailetMapper.insert(detail);
            if (result <= 0) {
                throw new RuntimeException("Failed to insert: " + detail); // 抛出异常，触发事务回滚
            }
        }

        return true; // 所有记录插入成功
    }

    @Override
    public List<OrderDetailet> listOrderDetailetByOrderId(Integer orderId) {
        QueryWrapper<OrderDetailet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", orderId);
        return orderDetailetMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean updateOrderStatus(Integer orderStatus, Integer id) {
        Orders orders = Orders.builder().orderId(id).orderState(orderStatus).build();
        int i = ordersMapper.updateById(orders);
        return i>0;
    }
}
